#include "datastorer.h"
#include <chrono>
#include <sstream>
#include <QDebug>
#include <QDateTime>

std::unique_ptr<DataStorer> DataStorer::dataStorer;
std::once_flag              DataStorer::itsOnceFlag;

DataStorer& DataStorer::instance()
{
    std::call_once(itsOnceFlag, [](){
        dataStorer = std::make_unique<DataStorer>();
    });
    return *dataStorer;
}

void DataStorer::open()
{
    if(!itsFile.is_open())
    {
        // 1. 打开文件（如果不存在则创建，存在则覆盖）
        auto now = std::chrono::system_clock::now();
        std::time_t now_time = std::chrono::system_clock::to_time_t(now);
        std::stringstream sstr;
        sstr << now_time << ".txt";
        itsFile.open(sstr.str());
    }
}

void DataStorer::write(float value)
{
    open();
    auto now = std::chrono::system_clock::now();
    QDateTime currentDateTime = QDateTime::currentDateTime();
    std::stringstream sstr;
    sstr << currentDateTime.date().year() << "-";
    sstr << currentDateTime.date().month() << "-";
    sstr << currentDateTime.date().day() << " ";
    sstr << currentDateTime.time().hour() << ":";
    sstr << currentDateTime.time().minute() << ":";
    sstr << currentDateTime.time().second() << ".";
    sstr << currentDateTime.time().msec() << "\t\t";
    sstr << value << "\n";
    // qDebug() << sstr.str();
    itsFile << sstr.str();
}

void DataStorer::write(float Progress, float value)
{
    open();
    std::stringstream sstr;
    sstr << Progress << " : ";
    sstr << value << "\n";
    itsFile << sstr.str();
}

void DataStorer::close()
{
    if(itsFile.is_open())
    {
        itsFile.close();
    }
}
